package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.constants.WmUserConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.threadlocal.WmThreadLocalUtils;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    FileStorageService fileStorageService;

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;
    @Value("${file.oss.web-site}")
    String webSite;
    @Value("${file.oss.profix}")
    String profix;

    @Override
    @Transactional
    public ResponseResult uploadPicture( MultipartFile multipartFile) {
        //1.判斷当前文件是否为空
        if(multipartFile.isEmpty()){
            //文件为空报参数错误
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.判断当前用户是否登录
        if(WmThreadLocalUtils.getUser()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.将文件上传到OSS上去
        String originalFilename = multipartFile.getOriginalFilename();
        String replace = UUID.randomUUID().toString().replace("-", "");
        String fileName=replace+originalFilename.substring(originalFilename.lastIndexOf("."));
        System.out.println(fileName);
        String store=null;
        try {
            InputStream inputStream = multipartFile.getInputStream();
//            System.out.println(profix);
            store= fileStorageService.store(profix, fileName, inputStream);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("这玩意儿哪里有报错:{}",e.getCause());
        }
        //4.文件保存到素材库中去
        WmMaterial wmMaterial=new WmMaterial();
        //todo:这个东西能够getApUserId是1102,getId是null
        Integer id = WmThreadLocalUtils.getUser().getId();
        System.out.println(id);
        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        wmMaterial.setUserId(id);
        wmMaterial.setCreatedTime(new Date());
        wmMaterial.setIsCollection(WmUserConstants.NOT_COLLECTION);
        wmMaterial.setType(WmUserConstants.PICTURE_TYPE);
        wmMaterial.setUrl(store);
        if(StringUtils.isBlank(store)){
            CustException.cust(AppHttpCodeEnum.UPLOAD_FILE_FAIL);
        }
        System.out.println(wmMaterial);
        save(wmMaterial);
        wmMaterial.setUrl(webSite+store);
        //5.修改WmMaterial的地址内容并把它返回至前端
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findPageList(WmMaterialDto dto) {
        //1.参数校验
        if(dto==null){
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(dto.getPage()==null||dto.getSize()==null){
            dto.checkParam();
        }
        LambdaQueryWrapper<WmMaterial> wrapper=new LambdaQueryWrapper<WmMaterial>();
        //2.逻辑校验
        if(dto.getIsCollection().equals(WmUserConstants.IS_COLLECTION)){
            //如果这个值是1的话,就把这个条件查询给加上
            wrapper.eq(WmMaterial::getIsCollection,WmUserConstants.IS_COLLECTION);
        }
        Integer wmUserId = WmThreadLocalUtils.getUser().getId();
        if(wmUserId==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        wrapper.eq(WmMaterial::getUserId,wmUserId);
        IPage<WmMaterial> pageParme=new Page<>(dto.getPage(),dto.getSize());
        IPage<WmMaterial> page = page(pageParme, wrapper);
        List<WmMaterial> records = page.getRecords();
        List<WmMaterial> list=new ArrayList<>();
        for (WmMaterial record : records) {
            String url = record.getUrl();
            record.setUrl(webSite+url);
            list.add(record);
        }
        ResponseResult responseResult=new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal(),list);
        //3.返回参数
        return responseResult;
    }

    @Override
    public ResponseResult delete(Integer id) {
        //刪除图片
        //1.校验参数
        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根據id獲取,且不能夠被收厰
        WmMaterial one = getOne(Wrappers.<WmMaterial>lambdaQuery().
                eq(WmMaterial::getId, id).
                ne(WmMaterial::getIsCollection,WmUserConstants.IS_COLLECTION));
        if(one==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Integer userId = one.getUserId();
        if (userId==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST_OR_COLLECTION);
        }
        LambdaQueryWrapper<WmNewsMaterial> wrapper=new LambdaQueryWrapper<WmNewsMaterial>();
        wrapper.eq(WmNewsMaterial::getMaterialId,id);
        List<WmNewsMaterial> wmNewsMaterials = wmNewsMaterialMapper.selectList(wrapper);
        if(wmNewsMaterials.size()>0){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_ISUSED_UNABLEDELETE);
        }
        removeById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏与取消收藏
     *
     * @param id
     * @param type
     * @return
     */
    @Override
    public ResponseResult updateCollectionStatus(Integer id, Short type) {
        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        Integer userId = WmThreadLocalUtils.getUser().getId();
        LambdaQueryWrapper<WmMaterial> wrapper=new LambdaQueryWrapper<WmMaterial>();
        wrapper.eq(WmMaterial::getId,id).eq(WmMaterial::getUserId,userId);
        WmMaterial one = getOne(wrapper);
        if (one==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        one.setIsCollection(type);
        updateById(one);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


}